<!-- 员工管理列表 -->
<template>
  <div class="content">
    <!-- 筛选栏 -->
    <search-form ref="searchForm" :dataFilterShow="false">
      <div>
        <el-form-item label="手机号:" prop="mobile">
          <el-input
            v-model="filterData.mobile"
            clearable
            placeholder="手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="员工姓名:" prop="fullName">
          <el-input
            v-model="filterData.fullName"
            clearable
            placeholder="员工姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="deptIds">
          <el-cascader
            :props="propss"
            :options="deptList"
            v-model="filterData.deptIds"
            clearable
          >
          </el-cascader>
        </el-form-item>
      </div>
      <div slot="tool">
        <el-button type="primary" @click="upDateStaff(1, {})">新增</el-button>
        <el-button @click="getDataList">查询</el-button>
      </div>
    </search-form>

    <!-- 列表栏 -->
    <filter-table
      :tableData="dataList.records"
      :pageData="dataList"
      @pageChange="pageChange"
      :loading="loading"
      ref="refFilterTable"
    >
      <template slot="table">
        <!-- <el-table-column prop="userNo" label="工号"></el-table-column> -->
        <el-table-column prop="fullName" label="姓名"></el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>
        <el-table-column prop="userName" label="登录名"></el-table-column>
        <el-table-column prop="deptName" label="部门"></el-table-column>
        <el-table-column prop="roleName" label="所属角色"></el-table-column>
        <el-table-column
          prop="createTime"
          label="首次加入时间"
          width="165"
        ></el-table-column>
        <el-table-column fixed="right" label="操作" width="160">
          <template slot-scope="{ row }">
            <el-button type="text" @click="upDateStaff(2, row)">修改</el-button>
            <el-button type="text" @click="editPass(row)">重置密码</el-button>
            <el-button
              type="text"
              @click="updateTypeUser(row)"
              :style="{ color: row.deleteStatus > 0 ? '' : '#FF6933' }"
              >{{ row.deleteStatus > 0 ? '启用' : '禁用' }}</el-button
            >
          </template>
        </el-table-column>
      </template>
    </filter-table>
    <!-- 新增编辑员工 -->
    <update-staff
      ref="staffDialog"
      :detailData="staffData"
      :isAdd="isAdd"
      :addEditVisible="addEditVisible"
    ></update-staff>
    <edit-pass
      ref="editDialog"
      :detailData="editData"
      :editVisible="editVisible"
    ></edit-pass>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { parseTime, formatTime } from '@/utils'
import SearchForm from '@/components/searchForm/searchTable'
import FilterTable from '@/components/filterTable/index'
import {
  getChildrenTmpListByPage,
  getChannelList,
  exportChildrenTmpList
} from '@/api/ucenter'
import { getUserList, updateTypeUser, getDeptList } from '@/api/rightsManage'
import UpdateStaff from './components/updateStaff'
import EditPass from './components/editPass'
export default {
  name: 'userCenterList',
  components: { SearchForm, FilterTable, UpdateStaff, EditPass },
  computed: {
    ...mapGetters(['name', 'userInfo'])
  },
  data() {
    return {
      loading: false,
      addEditVisible: false,
      editVisible: false,
      exportButtomLoading: false,
      lineList: [],
      deptList: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      filterData: {
        fullName: '',
        roleCode: '',
        userName: '',
        mobile: '',
        deptIds: [],
        deptId: ''
      },
      dataList: [],
      pagination: {
        page: 1,
        total: null,
        limit: 20
      },
      isAdd: 1,
      staffData: {},
      editData: {},
      propss: {
        lazy: false,
        value: 'deptId',
        label: 'deptName',
        children: 'childrens',
        expandTrigger: 'hover',
        checkStrictly: true
      }
    }
  },
  created() {
    this.getDeptList()
  },
  mounted() {
    this.getDataList()
  },
  methods: {
    // 获取列表数据
    getDataList() {
      this.loading = true
      getUserList(Object.assign({}, this.filterData, this.pagination)).then(
        res => {
          this.loading = false
          this.dataList = res.data
        }
      )
    },
    // 启用禁用
    async updateTypeUser({ userId, deleteStatus }) {
      let params = {
        userById: userId,
        deleteStatus: deleteStatus == 1 ? 0 : 1
      }

      await this.$confirm(
        `${deleteStatus == 1 ? '确定启用该账户？' : '确定禁用该账户？'}`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          updateTypeUser(params).then(res => {
            this.$message({
              message: deleteStatus == 1 ? '启用成功！' : '禁用成功！',
              type: 'success'
            })
            this.getDataList()
          })
        })
        .catch(() => {})
    },
    // 新增编辑员工
    upDateStaff(type, item) {
      this.isAdd = type
      this.staffData = Object.assign({}, item)
      this.$refs.staffDialog.addEditVisible = true
    },
    // 分页联动
    pageChange(pagedata) {
      setTimeout(() => {
        this.pagination = pagedata
      }, 1)
    },
    changePicker(res) {
      this.$refs['searchForm'].clearForm()
    },
    // 重置筛选
    resetFilterData() {
      this.filterData.chooseTime = ''
      this.filterData.channelIds = ''
      this.filterData.mobile = ''
    },
    // 修改密码
    editPass(item) {
      this.editData = Object.assign({}, item)
      this.$refs.editDialog.editVisible = true
    },
    // 获取部门列表
    getDeptList() {
      getDeptList({}).then(res => {
        this.lineList = res.data
        this.deptList = this.listConvertTree(res.data)
        if (this.isAdd == 2) {
          this.formdata.deptIds = this.getChildrenIds(this.detailData.deptId)
        }
      })
    },
    // 线性转树结构
    listConvertTree(data) {
      let parents = []

      //有父节点的数据
      let childrens = data.filter(
        value => value.parentId !== 'undefined' && value.parentId != null
      )

      let childrensCopy = JSON.parse(JSON.stringify(childrens))
      let childrensCopy1 = JSON.parse(JSON.stringify(childrensCopy))
      childrens.forEach((item1, index1) => {
        childrensCopy1.forEach((item2, index2) => {
          if (item1.parentId == item2.deptId && index1 != index2) {
            childrensCopy.splice(childrensCopy.indexOf(item2), 1)
          }
        })
      })

      parents = childrensCopy

      // console.log(childrens)
      //定义转换方法的具体实现
      let translator = (parents, childrens) => {
        //遍历父节点数据
        parents.forEach(parent => {
          //遍历子节点数据
          childrens.forEach((current, index) => {
            //此时找到父节点对应的一个子节点
            if (current.parentId === parent.deptId) {
              //对子节点数据进行深复制，这里只支持部分类型的数据深复制，对深复制不了解的童靴可以先去了解下深复制
              let temp = JSON.parse(JSON.stringify(childrens))
              //让当前子节点从temp中移除，temp作为新的子节点数据，这里是为了让递归时，子节点的遍历次数更少，如果父子关系的层级越多，越有利
              temp.splice(index, 1)
              //让当前子节点作为唯一的父节点，去递归查找其对应的子节点
              translator([current], temp)
              //把找到子节点放入父节点的childrens属性中
              typeof parent.childrens !== 'undefined'
                ? parent.childrens.push(current)
                : (parent.childrens = [current])
            }
          })
        })
      }
      //调用转换方法
      translator(parents, childrens)
      console.log('parents', parents)
      //返回最终的结果
      return parents
    }
  },
  watch: {
    'filterData.deptIds': {
      deep: true,
      handler(now, old) {
        if (now) {
          this.filterData.deptId = now[now.length - 1]
        } else {
          this.filterData.deptId = ''
        }
      }
    },
    filterData: {
      deep: true,
      handler(now, old) {
        this.pagination.page === 1
          ? this.getDataList()
          : (this.pagination.page = 1)
      }
    },
    pagination: {
      deep: true,
      handler(now, old) {
        this.getDataList()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
// .filterForm{
//   display: flex;
//   flex-direction: row;
//   justify-content: space-between;
// }
// .el-form-item{
//     margin-bottom: 0!important;
//   }
</style>
